package middleware

import (
	"encoding/gob"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type LoginMiddlewareBuilder struct {
	//paths []string
}

func NewLoginMiddlewareBuilder() *LoginMiddlewareBuilder {
	return &LoginMiddlewareBuilder{}
}

//func (l *LoginMiddlewareBuilder) IgnorePaths(path string) *LoginMiddlewareBuilder {
//	l.paths = append(l.paths, path)
//	return l
//}

func test111() {
	n := NewLoginMiddlewareBuilder()
	n.CheckLogin()
}

func (b *LoginMiddlewareBuilder) Name() {

}

func (m *LoginMiddlewareBuilder) CheckLogin() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(ctx *gin.Context) {
		println("请求经过了checklogin")
		path := ctx.Request.URL.Path
		if path == "/users/signup" || path == "/users/login" {
			return
		}

		sess := sessions.Default(ctx)
		userId := sess.Get("userId")
		println("这是checklogin里面的id ", userId)
		if userId == nil {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		// 判断session距离过期时间还有多少  60秒刷新一次session
		now := time.Now()
		const updateTimeKey = "update_time"
		val := sess.Get(updateTimeKey)
		lastUpdateTime, ok := val.(time.Time)
		if !ok || now.Sub(lastUpdateTime) > time.Second*60 || val == nil {
			sess.Set(updateTimeKey, now)
			sess.Set("useId", userId)
			sess.Options(sessions.Options{
				MaxAge: 30,
			})
			if err := sess.Save(); err != nil {
				fmt.Println(err)
			}
		}

	}
}
